package vehement.game.entities;

import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;

import vehement.game.GameThread;
import vehement.game.Globals;
import vehement.game.TerrainType;
import vehement.game.AI.Path;
import vehement.game.graphics.Ob;
import vehement.game.interfaces.Drawable;
import vehement.game.interfaces.Updateable;

public class Player implements Drawable, Updateable {

	public float rotation;
	public Vector3f location;  	//this is where you are.
	public Vector3f destination;//This is the temporary goal.
	public Vector3f goal;		//This is the eventual goal (where you clicked)
	public String name;

	public float charspd;
	public Path path;



	public Player(){

		
		name = "Default";
		rotation = 0.f;
		
		location = new Vector3f(0.f, 0.f, 0.f);
		destination= null;
		goal = null;
	}

	public void draw() {
		// TODO Auto-generated method stub

		GL11.glPushMatrix();
		GL11.glTranslatef(location.x, location.y, location.z);
		GL11.glRotatef(rotation, 0, 0, 1);
		GL11.glCallList(Ob.cubeCL);
		GL11.glPopMatrix();
	}

	public void update(float delta) {
		// TODO Auto-generated method stub

		//update stats/ai
		//update move
		move(delta);
	}

	private void move(float delta){

		if (goal !=null){
			Vector3f heading = new Vector3f(0,0,0); //This is how far we are moving 
			if (destination != null){
				//check distance to turn
				if (heading.lengthSquared()  <= Globals.minDist){
					//if it is within turning, kill current destination and find a new one

					if(path.hasNext()){
						//if we have a path, find the next node
						destination.x = path.peek().getX();
						destination.y = path.remove().getY();
						destination.z = 0;
					}

				}
				//else continue on course
			}

			//move down course unless we hit something. then we need to recalculate our path
			Vector3f.sub(destination, location, heading);
			heading.normalise();
			heading.scale(charspd);

			//if its not floor, we are blocked.
			if (GameThread.world.a[Math.round(heading.x+location.x)][Math.round(heading.y+location.y)].type != TerrainType.floor){
				//Find a new path to ultimate destination.
				path = GameThread.world.aStar(Math.round(location.x), Math.round(location.y), Math.round(goal.x), Math.round(goal.y));
				//if no path exists, kill our destination.
				if (path == null){
					goal = null;
				}
			}
		}
	}
}
